<template>
	<view class="login-container">
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<u--form :model="loginForm" ref="uForm">
			<u-form-item label="用户名" label-width="50">
				<u-input v-model="loginForm.username" />
			</u-form-item>
			<u-form-item label="密码" label-width="50">
				<u-input type="password" v-model="loginForm.password" />
			</u-form-item>
		</u--form>
		<button type="primary" class="btn-login" @click="login">登 录</button>
		<button type="primary" class="btn-wxlogin" open-type="getUserInfo" @click="wxLogin">
			微信一键登录
		</button>
		<text class="tip-text">小帅，小美们登录更精彩😍</text>

	</view>
</template>

<script>
	export default {
		name: "my-login",
		data() {
			return {
				loginForm: {
					username: '',
					password: ''
				},
				userInfo: {
					id: '',
					nickname: '',
					avatar: ''
				},
			};
		},
		methods: {
			wxLogin() {
				let _this = this
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: function(loginRes) {
						uni.$http.get('/user/user/wx', {
							code: loginRes.code
						}).then(res => {
							console.log(res);
							console.log(res.data.data);
							if (res.data.code === 20000) {
								_this.userInfo.id = res.data.data.id
								_this.userInfo.nickname = res.data.data.nickname
								_this.userInfo.avatar = res.data.data.avatar
								uni.setStorageSync("authentication", res.data.data.token)
								uni.setStorageSync("userInfo", _this.userInfo)
								uni.switchTab({
									url: '/pages/home/home'
								})
							} else {
								uni.$showMsg(res.msg)
							}
						})


					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
						console.log(err);
					}
				});
			},
			async login() {
				if (!this.loginForm.username) {
					uni.$showMsg('用户名为空！')
					return
				}
				if (!this.loginForm.password) {
					uni.$showMsg('密码为空！')
					return
				}
				let {
					data: res
				} = await uni.$http.post('/user/user/login', this.loginForm)
				if (res.code === 20000) {
					this.userInfo.id = res.data.id
					this.userInfo.nickname = res.data.nickname
					this.userInfo.avatar = res.data.avatar
					uni.setStorageSync("authentication", res.data.token)
					uni.setStorageSync("userInfo", this.userInfo)
					uni.switchTab({
						url: '/pages/home/home'
					})
				} else {
					uni.$showMsg(res.msg)
				}
			},
		}

	}
</script>

<style lang="scss">
	.login-container {
		height: 750px;
		background-color: #f8f8f8;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.btn-login {
			width: 80%;
			border-radius: 100px;
			margin: 15px 0;
			background-color: #1296db;
		}

		.btn-wxlogin {
			width: 80%;
			border-radius: 100px;
			margin: 5px 0;
			background-color: #00c853;

		}

		.tip-text {
			font-size: 12px;
			color: gray;
		}
	}
</style>